<template>
  <div>
    <div ref="timetitle">{{ $route.params.time }}</div>
    <video ref="timevideo" width="1000" controls
      @error="handleVideoError"
      :style="{ display: videoError ? 'none' : 'block' }"
    >
      <source :src="videoUrl">
    </video>
    <img
        ref="errorImage"
        :src="errorImageUrl"
    :style="{ display: videoError ? 'block' : 'none', width: videoWidth + 'px' }"
    />
  </div>
</template>

<script>
export default {
  data() {
    return {
      videoUrl: '',
      videoError: false,
      errorImageUrl: '/temp/BiliBiliError.jpg',
      videoWidth: 1000
    };
  },
  watch: {
    '$route.params.time': {
      immediate: true,
      handler(newTime) {
        this.updateVideoUrl(newTime);
        this.updateVideoWidth();
        this.videoError = false;
        this.checkVideoUrlAccessibility();
      }
    }
  },
  mounted() {
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.updateVideoWidth);
    // 初始化时设置视频宽度
    this.updateVideoWidth();
  },
  beforeDestroy() {
    // 组件销毁前移除窗口大小变化事件监听
    window.removeEventListener('resize', this.updateVideoWidth);
  },
  methods: {
    updateVideoUrl(time) {
      const strUrl = `/test1/temp/${time}.mp4`;
      console.log(strUrl);
      this.videoUrl = strUrl;
      if (this.$refs.timevideo) {
        this.$refs.timevideo.load();
      }
    },
    updateVideoWidth() {
      const windowWidth = window.innerWidth;
      let okWidth = 1000;
      if (windowWidth > 1000) {
        okWidth = windowWidth - 430;
      }
      if (this.$refs.timevideo) {
        this.$refs.timevideo.style.width = `${okWidth}px`;
      }
      if (this.$refs.errorImage) {
        // 设置错误图片的宽度
        this.$refs.errorImage.style.width = `${okWidth}px`;
      }
    },
    // 处理视频加载错误的方法
    handleVideoError() {
      // 当视频加载出错时，将视频错误状态设置为 true
      console.log("error");
      this.videoError = true;
    },
    async checkVideoUrlAccessibility() {
      try {
        const response = await fetch(this.videoUrl, { method: 'HEAD' });
        if (!response.ok) {
          this.videoError = true;
        } else {
          if (this.$refs.timevideo) {
            this.$refs.timevideo.load();
          }
        }
      } catch (error) {
        this.videoError = true;
      }
    }
  }
};
</script>
